﻿namespace Ops.Host.Core.Services.Impl;

internal sealed class PtMarkingService : IPtMarkingService
{
    private readonly SqlSugarRepository<PtMarking> _markingRepo;

    public PtMarkingService(SqlSugarRepository<PtMarking> markingRepo)
    {
        _markingRepo = markingRepo;
    }

    public async Task AddMarkingAsync(PtMarking item)
    {
        item.MarkingTime = DateTime.Now;
        await _markingRepo.InsertAsync(item);
    }

    public async Task AddOrUpdateMarkingAsync(PtMarking item)
    {
        var marking = await _markingRepo.GetFirstAsync(s => s.SN == item.SN);
        if (marking != null)
        {
            marking.MarkingTime = DateTime.Now;
            await _markingRepo.UpdateAsync(marking);
            return;
        }

        item.MarkingTime = DateTime.Now;
        await _markingRepo.InsertAsync(item);
    }

    public async Task<PagedList<PtMarking>> GetPagedListAsync(MakingFilter filter, int pageIndex, int pageSize)
    {
        return await _markingRepo.AsQueryable()
                .WhereIF(!string.IsNullOrWhiteSpace(filter.SN), s => s.SN.Contains(filter.SN!))
                .WhereIF(!string.IsNullOrWhiteSpace(filter.ProductType), s => s.ProductType == filter.ProductType)
                .WhereIF(!string.IsNullOrWhiteSpace(filter.MarkerNo), s => s.MarkerNo == filter.MarkerNo)
                .WhereIF(filter.MarkingTimeStart != null, s => s.MarkingTime >= filter.MarkingTimeStart.ToDayMin())
                .WhereIF(filter.MarkingTimeEnd != null, s => s.MarkingTime <= filter.MarkingTimeEnd.ToDayMax())
                .ToPagedListAsync(pageIndex, pageSize);
    }
}
